package Logic.dbUtils;

import Logic.constant.C;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liujun
 * @version V1.0
 * @date 2022/3/12 6:21 PM
 * @author-Email ljfirst@mail.ustc.edu.cn
 * @description MySqlConnection 类
 */
public class MySqlConnection {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        new MySqlConnection().SqlConnection();
    }

    /*
     *java连接mysql数据库
     *1、加载驱动程序
     *2、数据库连接字符串"jdbc:mysql://localhost:3306/数据库名?"
     *3、数据库登录名
     *3、数据库登录密码
     */
    Connection conn = null;

    public List<SQLTestDataEntity> execSql(String tableName, String className) throws SQLException {
        SqlConnection();
        Statement stmt = (Statement) conn.createStatement();
        String sql = "SELECT * FROM AlgorithmPracticeDB." + tableName + " where  \"" + className + "\" rlike class_name";
        List<SQLTestDataEntity> list = new ArrayList<>();
        System.out.println(sql);
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            list.add(new SQLTestDataEntity(rs.getInt("id"), rs.getString("input"), rs.getString("output"), rs.getString("class_name")));
        }
        closeConn();
        return list;
    }

    public Connection SqlConnection() {
        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("未能成功加载驱动程序，请检查是否导入驱动程序！");
            //添加一个println，如果加载驱动异常，检查是否添加驱动，或者添加驱动字符串是否错误
            e.printStackTrace();
        }

        try {
            conn = (Connection) DriverManager.getConnection(C.URL, C.NAME, C.PASSWORD);
            System.out.println("获取数据库连接成功！");
        } catch (SQLException e) {
            System.out.println("获取数据库连接失败！");
            //添加一个println，如果连接失败，检查连接字符串或者登录名以及密码是否错误
            e.printStackTrace();
        }
        return conn;
    }

    public void closeConn() {
        //数据库打开后就要关闭
        if (conn != null) {
            try {
                conn.close();
                System.out.println("数据库关闭成功！");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                conn = null;
            }
        }
    }
}


